﻿using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using System.Data;

namespace Himp.TaskScheduling
{
    /// <summary>
    /// 制样完成后生成标准化验任务
    /// 测试
    /// </summary>
    public class TempAutoStandardTestTaskWorker : IHostedService
    {
        #region SQL

        //获取化验结果
        public const string GET_SAMPLE_PREPARATION_RESULT_SQL = @"
            SELECT *
            FROM [TaskScheduling].[TS_SamplePreparationResult]
            WHERE FORMAT(Endtime, 'yyyy-MM-dd') = FORMAT(GETDATE(), 'yyyy-MM-dd')
            ";

        public const string EXIST_STANDARD_TEST_FLAG_SQL = @"
            SELECT CASE WHEN 
            EXISTS (SELECT 1 FROM [TaskScheduling].[TS_StandardTestTasks] WHERE BottomCode = @BottomCode) 
            THEN 1 
            ELSE 0 
            END";

        public const string INSERT_STANDARD_TEST_TASK_SQL = @"
            INSERT INTO
            [TaskScheduling].[TS_StandardTestTasks]
            (
            SampleCode,
            TestCode,
            BottomCode,
            Sampletype,
            TaskType,
            SampeWay,
            TestCnt,
            TaskAssgnTime,
            LastOperTime,
            ExecStas
            )
            VALUES
            (
            @SampleCode,
            @TestCode,
            @BottomCode,
            @Sampletype,
            @TaskType,
            @SampeWay,
            @TestCnt,
            GETDATE(),
            GETDATE(),
            @ExecStas
            )
            ";

        #endregion

        #region 字段

        private readonly ConnectionStringOption _connectionStrings;
        private ILogger<TempAutoStandardTestTaskWorker> _logger;

        #endregion

        #region 方法

        public TempAutoStandardTestTaskWorker(ILogger<TempAutoStandardTestTaskWorker> logger
            ,IOptions<ConnectionStringOption> connectionStrings)
        {
            _logger = logger;
            _connectionStrings = connectionStrings.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("--------标准制样任务开始启动--------");

            try
            {
                using (IDbConnection connection = new SqlConnection(_connectionStrings.RL_Web))
                {
                    connection.Open();
                    // 读取数据
                    var samplePreparationResultList = connection.Query<SamplePreparationResult>(GET_SAMPLE_PREPARATION_RESULT_SQL);

                    foreach (var item in samplePreparationResultList)
                    {
                        if (!string.IsNullOrEmpty(item.BottomCode21) && item.Weight21Bottles != 0)
                        {
                            bool exists = await connection.ExecuteScalarAsync<bool>(EXIST_STANDARD_TEST_FLAG_SQL,
                                new { BottomCode = item.BottomCode21 });

                            if (!exists)
                            {
                                var codeStas = await connection.ExecuteAsync(INSERT_STANDARD_TEST_TASK_SQL,
                                    new
                                    {
                                        SampleCode = item.Id,
                                        TestCode = item.Id,
                                        BottomCode = item.BottomCode21,
                                        Sampletype = "0.2mm",
                                        TaskType = 0,
                                        SampeWay = "自动",
                                        TestCnt = 0,
                                        ExecStas = "未就绪"
                                    });
                                _logger.LogInformation($"{item.BottomCode21}:{codeStas}");
                            }
                            else
                            {
                                _logger.LogInformation($"{item.BottomCode21}:已添加");
                            }
                        }

                        if (!string.IsNullOrEmpty(item.BottomCode61) && item.Weight61Bottles != 0)
                        {
                            bool exists = await connection.ExecuteScalarAsync<bool>(EXIST_STANDARD_TEST_FLAG_SQL,
                                new { BottomCode = item.BottomCode61 });

                            if (!exists)
                            {
                                var codeStas = await connection.ExecuteAsync(INSERT_STANDARD_TEST_TASK_SQL,
                                    new
                                    {
                                        SampleCode = item.Id,
                                        TestCode = item.Id,
                                        BottomCode = item.BottomCode61,
                                        Sampletype = "6mm",
                                        TaskType = 0,
                                        SampeWay = "自动",
                                        TestCnt = 0,
                                        ExecStas = "未就绪"
                                    });
                                _logger.LogInformation($"{item.BottomCode61}:{codeStas}");
                            }
                            else
                            {
                                _logger.LogInformation($"{item.BottomCode61}:已添加");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogInformation("--------标准制样任务异常--------");
                _logger.LogInformation(e.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        #endregion
    }
}
